package com.alliky.core.data.mediator

import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadType
import androidx.paging.PagingState
import androidx.paging.RemoteMediator
import androidx.room.withTransaction
import com.rrc.common.api.ApiService
import com.alliky.core.data.db.AppDatabase
import com.rrc.common.entity.CategoryVO
import com.rrc.common.entity.RemoteKey

/**
 * ================================================
 * @Description: 描述
 * @Author: wxianing
 * @Date: 2023/2/9 10:30
 * ================================================
 */
@OptIn(ExperimentalPagingApi::class)
class CategoryRemoteMediator(private val api: ApiService, private val db: AppDatabase) :
    RemoteMediator<Int, CategoryVO>() {

    companion object {
        var SUBREDDIT = this.javaClass.simpleName
    }

    private val remoteKeyDao = db.remoteKeyDao()

    override suspend fun load(
        loadType: LoadType,
        state: PagingState<Int, CategoryVO>
    ): MediatorResult {
        try {
            val pageKey: Int? = when (loadType) {
                LoadType.REFRESH -> 1
                LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
                LoadType.APPEND -> {
                    val remoteKey = db.withTransaction {
                        remoteKeyDao.remoteKeyByPost(SUBREDDIT)
                    }
                    if (remoteKey.nextKey == null) {
                        return MediatorResult.Success(endOfPaginationReached = true)
                    }
                    remoteKey.nextKey
                }
            }

            val pageSize = when (loadType) {
                LoadType.REFRESH -> state.config.initialLoadSize
                else -> state.config.pageSize
            }.toString()

            val param = mapOf(
                Pair("pageNum", pageKey.toString()),
                Pair("pageSize", pageSize)
            )

            val response = api.getCategory(param)
            val result = response.data

            db.withTransaction {
                if (loadType == LoadType.REFRESH) {
                    db.categoryDao().clear()
                    db.remoteKeyDao().deleteBySubreddit(SUBREDDIT)
                }

                val pageNum = param["pageNum"].toString()

                remoteKeyDao.insert(RemoteKey(SUBREDDIT, pageNum.toInt() + 1))
                db.categoryDao().insert(response.data ?: emptyList())
            }

            return MediatorResult.Success(endOfPaginationReached = result.isNullOrEmpty())
        } catch (e: Exception) {
            return MediatorResult.Error(e)
        }
    }
}